package com.yuan.ayuancity.controller.common;

import com.sun.deploy.net.HttpResponse;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.ChineseGifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import com.yuan.view.YuancityView;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *      生成验证码,采用了github的com.wf.captcha简单方便
 * </p>
 *
 * @author asuyuan
 * @since 2023/2/8
 */
@Api(tags = "验证码控制器")
@RestController
@RequestMapping("/city/v1")
@CrossOrigin
public class CaptchaController {
    public static final String VERIFY_CODE_IN_SESSION_KEY = "captcha";
    public static final String REQUEST_VERIFY_CODE_PARAMETER = "code";

    @GetMapping("/getCaptcha")
    public YuancityView getCaptcha(HttpServletRequest request, HttpServletResponse response,@RequestParam(required = false) String type ) {
        // ChineseCaptcha captcha = new ChineseCaptcha(130, 48, 4);//汉字验证码
        // ChineseGifCaptcha captcha = new ChineseGifCaptcha(130,48,4);//动态汉字
        // ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48, 2);//算术
        SpecCaptcha captcha = new SpecCaptcha(130, 48, 4);//字母数字
        String code = captcha.text();
        System.out.println("验证码 :" + code);
        //存放到sesiion
        response.setHeader("Access-Control-Allow-Credentials","true");
        request.getSession().setAttribute(VERIFY_CODE_IN_SESSION_KEY, code);
        request.getSession().setMaxInactiveInterval(60 * 3);//设置session过期时间，以秒为单位
        //输出给客户端
        try {
            // 验证码存入redis
            // 将uuid作为redis的key
            // String key = UUID.randomUUID().toString();
            //
            // String code = captcha.text().toLowerCase();
            //
            //     redisCache.setCacheObject(key,code,1, TimeUnit.MINUTES);
            //
            //             Map<String, Object> map = new HashMap<>();
            //
            //     map.put("key",key);
            //     map.put("code",captcha.toBase64());

           if ( type!=null&&type.equals("houtai")){
               //后台
               return YuancityView.success("获取验证码成功").put("code", captcha.toBase64());
           }else {
               //前台
               CaptchaUtil.out(captcha,request,response); //直接放到url

           }
        } catch (Exception e) {
            System.out.println("验证码获取异常,请检查common~" + e.getMessage());
            e.printStackTrace();
        }
        return YuancityView.failure("获取验证码失败");
    }
}